package com.v2.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.widget.DatePicker;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.jakewharton.rxbinding3.view.RxView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.v2.request.RequestCenter;
import com.v2.utils.TSP;
import com.v2.utils.TToast;
import com.v2.utils.okhttp.OkHttpRequestCallback;
import com.zou.lotterylucky.R;
import com.zou.lotterylucky.activity.DealsAdapter;
import com.zou.lotterylucky.data.Order;
import com.zou.lotterylucky.databinding.ActivityRedeemBinding;
import com.zou.lotterylucky.utils.AidlUtil;
import com.zou.lotterylucky.utils.TimeCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RedeemActivity extends BaseActivity<ActivityRedeemBinding> {

    private DealsAdapter adapter;
    private List<Order> ordersData = new ArrayList<>();


    @Override
    protected int layoutId() {
        return R.layout.activity_redeem;
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onCreate() {
        mBinding.topbar.setTitle(R.string.redeem);
        mBinding.topbar.addLeftBackImageButton().setOnClickListener(v -> onBackPressed());

        mBinding.searchBtn.setOnClickListener(v -> loadOrders());
        mBinding.scanBtn.setOnClickListener(v -> {
            new IntentIntegrator(this).setDesiredBarcodeFormats(IntentIntegrator.QR_CODE).initiateScan();
        });

        adapter = new DealsAdapter(ordersData);
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.setAdapter(adapter);

        adapter.setOnItemChildClickListener((adapter, view, position) -> {
            Intent intent = new Intent(this, OrderDetailActivity.class);
            selectedOrder = (Order) adapter.getData().get(position);
            intent.putExtra("from", 0);
            startActivity(intent);
        });

        AidlUtil.Companion.getInstance().getTime("yyyy-MM-dd", new TimeCallBack() {
            @Override
            public void onError(String msg) {
                TToast.show(msg);
            }

            @Override
            public void onSuccess(String time) {
                try {
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = dateFormat.parse(time);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.DATE, -1);
                    String resultTime = dateFormat.format(calendar.getTime());
                    mBinding.tvTimeStart.setText(resultTime);
                    mBinding.tvTimeEnd.setText(resultTime);
                } catch (Exception e) {
                    TToast.show(e.toString());
                }
            }
        });

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener dateSetListener = (new DatePickerDialog.OnDateSetListener() {
            public final void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                mBinding.tvTimeStart.setText(dateFormat.format(calendar.getTime()));
            }
        });

        RxView.clicks(mBinding.tvTimeStart).throttleFirst(1000, TimeUnit.MILLISECONDS).subscribe(unit -> new DatePickerDialog(this, dateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show());

        DatePickerDialog.OnDateSetListener dateSetListener1 = (new DatePickerDialog.OnDateSetListener() {
            public final void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                mBinding.tvTimeEnd.setText(dateFormat.format(calendar.getTime()));
            }
        });

        RxView.clicks(mBinding.tvTimeEnd).throttleFirst(1000, TimeUnit.MILLISECONDS).subscribe(unit -> new DatePickerDialog(this, dateSetListener1, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show());

        loadOrders();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result != null) {
            String contents = result.getContents();
            try {
                JSONObject jsonObject = new JSONObject(contents);
                String number = jsonObject.getString("or");
                String machineNumber = TSP.getInstance().getString("username", "0001");
                String tag = number.substring(0, machineNumber.length());
                if (tag != machineNumber) {
                    TToast.show("机号不符");
                    return;
                }
                loadOrderByNumber(number);

            } catch (JSONException e) {
                e.printStackTrace();
                TToast.show(getString(R.string.error_qr));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void loadOrders() {
        RequestCenter.appGetOrders(TSP.getInstance().getString("username"), "", "", "", "", new OkHttpRequestCallback() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onFailure(String error) {
                TToast.show(error);
            }
        });
    }


    private void loadOrderByNumber(String number) {
        KProgressHUD hud = KProgressHUD.create(this);
        hud.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
        hud.setCancellable(false);
        hud.setAnimationSpeed(2);
        hud.setDimAmount(0.5f);
        hud.show();
        RequestCenter.getOrderBySerialNumber(TSP.getInstance().getString("username"), number, new OkHttpRequestCallback() {
            @Override
            public void onSuccess(String result) {
                hud.dismiss();
            }

            @Override
            public void onFailure(String error) {
                hud.dismiss();
                TToast.show(error);
            }
        });
    }
}
